﻿using DFGK_WMS.IRepository;
using DFGK_WMS.Model;
using DFGK_WMS.Model.Models;
using DFGK_WMS.WebAPI.Controllers.Result;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;

namespace DFGK_WMS.WebAPI.Controllers.库存管理
{
    /// <summary>
    /// 库存查询
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class InventoryQueryController : ControllerBase
    {
        private readonly ITWarehouseRepository tWarehouseRy;
        private readonly ITInventoryRepository tInventoryRy;

        public InventoryQueryController(ITWarehouseRepository tWarehouseRy, ITInventoryRepository tInventoryRy)
        {
            this.tWarehouseRy = tWarehouseRy;
            this.tInventoryRy = tInventoryRy;
        }

        /// <summary>
        /// 仓库下拉框
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetWarehouse()
        {
            try
            {
                var res = tWarehouseRy.GetAll().AsNoTracking().Select(s => new { s.Name, s.Code, s.Id });
                return Ok(BaseResult.Result(res, "200"));
            }
            catch (Exception)
            {
                return Ok(BaseResult.Result(false, "系统错误", "500"));
            }
        }

        /// <summary>
        /// 库存汇总
        /// </summary>
        /// <param name="owerId"></param>
        /// <param name="whId"></param>
        /// <param name="wlName"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTInventoryPage(int? owerId, int? whId, string? wlName, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            try
            {
                var res = tInventoryRy.GetTInventoryPage(out var totalCount, owerId, whId, wlName, pageIndex, pageSize);
                return Ok(BaseResult.Result(res, "200", totalCount));
            }
            catch (Exception)
            {

                throw;
            }
        }
        /// <summary>
        /// 库存明细
        /// </summary>
        /// <param name="owerId"></param>
        /// <param name="whId"></param>
        /// <param name="wlName"></param>
        /// <param name="kcState"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetTInventoryDtoPage(int? owerId, int? whId, string? wlName, int? kcState, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                BaseResult.Result("400", "分页条件有误！");
            }
            try
            {
                var res = tInventoryRy.GetTInventoryDtoPage(out var totalCount, owerId, whId, wlName, kcState, pageIndex, pageSize);
                return Ok(BaseResult.Result(res, "200", totalCount));
            }
            catch (Exception)
            {

                throw;
            }
        }
        MemoryStream ProcessExcelData()
        {
            //模块从表中读取的数据
            List<TInventory> list = new List<TInventory>();
            list = tInventoryRy.GetTInventoryExcel();
            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("库存汇总");  // 创建Excel中的表对象
                                                           //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("物料名称"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("物料号");
            row0.CreateCell(2).SetCellValue("货主");
            row0.CreateCell(3).SetCellValue("数量");
            row0.CreateCell(4).SetCellValue("总价");
            var rowIndex = 1;
            foreach (var item in list)
            {
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(item.MaterialName);
                row.CreateCell(1).SetCellValue(item.MaterialCode);
                row.CreateCell(3).SetCellValue(item.AvailableQty.ToString() ?? "NULL");
                row.CreateCell(4).SetCellValue(item.TotalPrice.ToString() ?? "NULL");
                rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        /// <summary>
        /// 导出库存汇总
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult DownTin()
        {
            MemoryStream ms = ProcessExcelData();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "库存汇总.xlsx"); //关键语句
        }
        MemoryStream ProcessExcel()
        {
            //模块从表中读取的数据
            List<TInventory> list = new List<TInventory>();
            list = tInventoryRy.GetTInventoryExcel();

            var materialCategoryList = tInventoryRy.GetMaterialCategoryGroups();

            // 已经读取出了正确的数据后
            //创建Excel对象把数据赋值到对象中
            IWorkbook workbook = new XSSFWorkbook(); // Excel对象
            ISheet sheet1 = workbook.CreateSheet("库存明细");  // 创建Excel中的表对象
                                                           //表头
            IRow row0 = sheet1.CreateRow(0);  // 在sheet1表格中创建第0行
            row0.CreateCell(0).SetCellValue("装备类型"); // 在sheet1表格中第0行创建第0列，并且在给这个单元格赋值
            row0.CreateCell(1).SetCellValue("装备名称");
            row0.CreateCell(2).SetCellValue("器材名称");
            row0.CreateCell(3).SetCellValue("器材代码");
            row0.CreateCell(4).SetCellValue("规格型号");
            row0.CreateCell(5).SetCellValue("质量等级");
            row0.CreateCell(6).SetCellValue("计量单位");
            row0.CreateCell(7).SetCellValue("库存数量");
            row0.CreateCell(8).SetCellValue("存放位置");
            row0.CreateCell(9).SetCellValue("单价");
            row0.CreateCell(10).SetCellValue("总价");


            var rowIndex = 1;
            foreach (var item in list)
            {

                var materialCategoryModel = materialCategoryList.Where(x => x.Id == item.MaterialCategoryId);
                if(materialCategoryModel.Count() <= 0)
                {
                    continue;
                }
                IRow row = sheet1.CreateRow(rowIndex);
                row.CreateCell(0).SetCellValue(materialCategoryModel.FirstOrDefault().EquipmentType);
                row.CreateCell(1).SetCellValue(item.MaterialCategoryName);
                row.CreateCell(2).SetCellValue(item.MaterialName);
                row.CreateCell(3).SetCellValue(item.MaterialCode);
                row.CreateCell(4).SetCellValue(item.ModelSpec);
                string qualityStateName = "";
                switch (item.QualityState)
                {
                    case 0:
                        qualityStateName = "新品";
                        break;
                    case 1:
                        qualityStateName = "堪用品";
                        break;
                    case 2:
                        qualityStateName = "待修品";
                        break;
                    case 3:
                        qualityStateName = "废品";
                        break;
                    default:
                        qualityStateName = "其他";
                        break;
                }
                row.CreateCell(5).SetCellValue(qualityStateName);

                row.CreateCell(6).SetCellValue(item.UnitName);
                row.CreateCell(7).SetCellValue(item.AvailableQty.ToString() ?? "NULL");
                row.CreateCell(column: 8).SetCellValue(item.LocationCode);
                double price = item.Price.HasValue ? (double)item.Price.Value : 0;
                double availableQty = (double)item.AvailableQty.GetValueOrDefault();
                double result = availableQty * price;
                row.CreateCell(column: 9).SetCellValue(price);
                row.CreateCell(10).SetCellValue(result); rowIndex++;
            }
            MemoryStream ms = new MemoryStream();
            workbook.Write(ms);

            return ms;
        }
        /// <summary>
        /// 导出库存明细
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public FileContentResult DownTinM()
        {
            MemoryStream ms = ProcessExcel();
            byte[] fileBytes = ms.ToArray();
            return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "库存明细.xlsx"); //关键语句
        }

        /// <summary>
        /// 器材库存显示
        /// </summary>
        /// <param name="mname"></param>
        /// <param name="pageIndex"></param>
        /// <param name="pageSize"></param>
        /// <returns></returns>
        [HttpGet]
        public IActionResult GetXTinventoryList(string? mname, int pageIndex = 1, int pageSize = 10)
        {
            if (pageIndex <= 0 || pageSize <= 0)
            {
                return Ok(BaseResult.Result("400", "分页条件有误！"));
            }
            int totalCount;

            var list = tInventoryRy.GetXTinventoryList(mname, pageIndex, pageSize, out totalCount);
            if (list.Any())
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }


        [HttpGet]
        public IActionResult GetEquipmentQureys(int pageIndex, int pageSize)
        {
            int totalCount;
            var list = tInventoryRy.GetEquipmentQureys(pageIndex, pageSize, out totalCount);
            if (list != null || list.Count != 0)
            {
                return Ok(BaseResult.Result(list, "查询成功！", "200", totalCount));
            }
            return Ok(BaseResult.Result(null, "查询失败！", "500", 0));
        }

        [HttpPost]
        public IActionResult UpInventory(UpInventoryDto upInventoryDto)
        {
            int totalCount;
            foreach (var item in upInventoryDto.id)
            {
                var IsOk = tInventoryRy.UpInventory(item, upInventoryDto.qualityState, out string msg);
                if (!IsOk)
                    return Ok(BaseResult.Result(false, msg, "500"));

            }
            return Ok(value: BaseResult.Result(true, "更新成功！", "200"));


        }
    }
}
